package com.cms.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cms.common.AuthAccess;
import com.cms.common.QueryPageParam;
import com.cms.common.Result;
import com.cms.controller.dto.UserDTO;
import com.cms.entity.Menu;
import com.cms.entity.User;
import com.cms.service.IUserService;
import com.cms.service.MenuService;
import com.cms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private IUserService iUserService;

    @GetMapping("/list")
    public List<User> list(){
        return userService.list();
    }

    @GetMapping("/findByNo")
    public Result findByNo(@RequestParam String no){
        List list = userService.lambdaQuery().eq(User::getNo,no).list();
        return list.size()>0?Result.suc(list):Result.fail();
    }

    @PostMapping("/save")
    public Result save(@RequestBody User user){
        return userService.save(user)?Result.suc():Result.fail();
    }

    @PostMapping("/update")
    public Result update(@RequestBody User user){
        return userService.updateById(user)?Result.suc():Result.fail();
    }

    @GetMapping("/del")
    public Result del(@RequestParam String id){
        return userService.removeById(id)?Result.suc():Result.fail();
    }

//    @PostMapping("/login")
//    public Result login(@RequestBody User user){
//        List list = userService.lambdaQuery()
//                .eq(User::getNo,user.getNo())
//                .eq(User::getPassword,user.getPassword()).list();
//
//        if(list.size()>0){
//            User user1 = (User)list.get(0);
//            List menuList = menuService.lambdaQuery().like(Menu::getMenuright,user1.getRoleId()).list();
//            HashMap res = new HashMap();
//            res.put("user",user1);
//            res.put("menu",menuList);
//            return Result.suc(res);
//        }
//        return Result.fail();
//    }
    @PostMapping("/login")
    public Result login (@RequestBody UserDTO userDTO){
        String no = userDTO.getNo();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(no) ||StrUtil.isBlank(password)){
            return Result.fail();//这里用error用不了
        }
        UserDTO dto = iUserService.login(userDTO);

        return Result.suc(dto);
    //        return Result.suc(iUserService.register(userDTO));
    }
    //注册
    @PostMapping("/register")
    public Result register (@RequestBody UserDTO userDTO){
        String no = userDTO.getNo();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(no) ||StrUtil.isBlank(password)){
            return Result.fail();//这里用error用不了
        }
//        UserDTO dto = iUserService.login(userDTO);
//        return Result.suc(dto);
        return Result.suc(iUserService.register(userDTO));
    }



    @PostMapping("/mod")
    public boolean mod(@RequestBody User user){
        return userService.updateById(user);
    }

    @PostMapping("/saveOrMod")
    public boolean saveOrMod(@RequestBody User user){
        return userService.saveOrUpdate(user);
    }

    @GetMapping("/delete")
    public boolean delete(Integer id){
        return userService.removeById(id);
    }

    @PostMapping("/listP")
    public Result listP(@RequestBody User user){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(user.getName())){
            lambdaQueryWrapper.like(User::getName,user.getName());
        }

        return Result.suc(userService.list(lambdaQueryWrapper));
    }

    @PostMapping("/listPage")
    public List<User> listPage(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        System.out.println("name==="+(String)param.get("name"));

        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName,name);

        IPage result = userService.page(page,lambdaQueryWrapper);

        System.out.println("total=="+result.getTotal());

        return result.getRecords();
    }

    @PostMapping("/listPageC")
    public List<User> listPageC(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        System.out.println("name==="+(String)param.get("name"));

        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName,name);

        IPage result = userService.pageCC(page,lambdaQueryWrapper);

        System.out.println("total=="+result.getTotal());

        return result.getRecords();
    }

    @PostMapping("/listPageC1")
    public Result listPageC1(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        String sex = (String)param.get("sex");
        String roleId = (String)param.get("roleId");
        String phone = (String) param.get("phone");
        String no = (String) param.get("no");

        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(name) && !"null".equals(name)){
            lambdaQueryWrapper.like(User::getName,name);
        }
        if(StringUtils.isNotBlank(sex)){
            lambdaQueryWrapper.eq(User::getSex,sex);
        }
        if(StringUtils.isNotBlank(roleId)){
            lambdaQueryWrapper.eq(User::getRoleId,roleId);
        }
        if(StringUtils.isNotBlank(phone)){
            lambdaQueryWrapper.eq(User::getPhone, phone);
        }
        if(StringUtils.isNotBlank(no)){
            lambdaQueryWrapper.eq(User::getNo, no);
        }

        IPage result = userService.pageCC(page,lambdaQueryWrapper);

        System.out.println("total=="+result.getTotal());

        return Result.suc(result.getRecords(),result.getTotal());
    }


    @PostMapping("/updateAvatarUrl")
    public Result updateAvatarUrl(@RequestParam Integer id, @RequestParam String avatarUrl){
        User user = userService.getById(id);
        if (user == null) {
            return Result.fail();
        }
        user.setAvatarUrl(avatarUrl);
        return userService.updateById(user) ? Result.suc() : Result.fail();
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        //从数据库查询出所有的数据
        List<User> list = iUserService.list();
        //在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名，如果把这些注释掉，导出的表头就是数据库的字段
        writer.addHeaderAlias("id","用户ID");
        writer.addHeaderAlias("avatarUrl","头像地址");
        writer.addHeaderAlias("no","账号");
        writer.addHeaderAlias("name","用户名");
        writer.addHeaderAlias("password","密码");
        writer.addHeaderAlias("age","年龄");
        writer.addHeaderAlias("sex","性别");
        writer.addHeaderAlias("phone","电话号码");
        writer.addHeaderAlias("roleId","权限");
        writer.addHeaderAlias("isvalid","认证");

        //一次性写出list内的对象到excel,使用默认样式，强制输出标题
        writer.write(list,true);

        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();

    }

    /**
     * 导出接口
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //当表头是英文名才能用，导出的时候注释掉别名就好了
        List<User> list = reader.readAll(User.class);
        iUserService.saveBatch(list);
        return true;
    }

}

